<template>
  <div class="task-log">
    <data-code-editor ref="coder" :value="currentTab.content" />
  </div>
</template>
<script>
import DataCodeEditor from "../components/data-code-editor";
import { mapState } from "vuex";
export default {
  name: "TaskLog",
  components: { DataCodeEditor },
  data() {
    return {
      logs: []
    };
  },
  computed: {
    ...mapState({
      currentTab: ({ data }) => data.currentTab
    })
  },
  watch: {
    ["currentTab.id"] : {
      handler(id) {
        // this.clearTimer();
        // this.updateLog();
        this.rollLog();
      },

      immediate: true
    }
  },
  destroyed() {
    // this.clearTimer();
  },
  mounted() {
    this.updateLog();
    this.$bus.$on("refresh-task-log", () => {
      this.updateLog();
    });
  },
  methods: {
    updateLog() {
      if (!this.currentTab.hostname) {
        this.$nextTick(() => {
          if (this.$refs.coder){
            this.$refs.coder.setValue("", true, true);
          }
        });
        return;
      }
      this.$http.task.getTaskLog({ dag_id: this.currentTab.dag_id, task_id: this.currentTab.task_id }).then(res => {
        this.logs.push(...res);

        if (this.logs.length > 200) {
          this.logs = this.logs.slice(this.logs.length - 200, this.logs.length);
        }
        if(this.$refs.coder){
          this.$refs.coder.setValue(this.logs.join(" \n"), true, true);
        }
      });
    },
    rollLog() {
      this.$nextTick(() => {
        this.$refs.coder && this.$refs.coder.setValue("", true, true);
      });

      // this.timer = setInterval(this.updateLog, 60000);
    },
    clearTimer() {
      this.timer && clearInterval(this.timer);
      this.timer = null;
    }
  }
};
</script>
<style lang="scss">
.task-log {
  height: calc(100% - 16px);
  overflow: auto;
  .CodeMirror {
    height: 100%;
  }
}
</style>
